<template>
  <div>
    <FormPanel
      :list="topFilterList"
      :cols="3"
      :collapse="false"
      :isSubmitBtn="false"
      @filterChange="changeHandle"
      v-show="propstype=='add'"
    ></FormPanel>
    <FormPanel
      :list="formshowList"
      :cols="3"
      :collapse="false"
      :isSubmitBtn="false"
      @filterChange="changeHandle"
      v-show="propstype=='show'"
    ></FormPanel>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="已分配角色" name="first"></el-tab-pane>
      <el-tab-pane label="已分配组织" name="second"></el-tab-pane>
    </el-tabs>
    <!-- 分配角色 -->
    <div v-show="propstype=='add'&&activeName=='first'">
      <FilterTable
        ref="addtable"
        :columns="columns"
        :dataSource="addtablelist"
        :datakey="'records'"
        :onColumnsChange="columns => this.columns = columns"
        :uid="'_uid'"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addFun()">新增</el-button>
        </template>
      </FilterTable>
      <div
        :style="{
              position: 'absolute',
              left: 0,
              bottom: 0,
              right: 0,
              zIndex: 9,
              borderTop: '1px solid #e9e9e9',
              padding: '10px 20px',
              background: '#fff',
              textAlign: 'right'
            }"
      >
        <el-button @click="closeDrawer(1)">取 消</el-button>
        <el-button @click="closeDrawer(2)" type="primary">保 存</el-button>
      </div>
      <BaseDialog
        :visible.sync="visibleAdd"
        title="角色模板选择"
        destroyOnClose
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
      >
        <roleAdd @change="changepopHandle" @close="roleAddClose" />
      </BaseDialog>
    </div>
    <div v-show="propstype=='show'&&activeName=='first'">
      <FilterTable
        ref="showtable"
        :columns="columns1"
        :isPagination="false"
        :isSelectColumn="false"
        :dataSource="detailList"
        :uidkey="'_uid'"
        :onColumnsChange="columns1 => this.columns1 = columns1"
      ></FilterTable>
      <div
        :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'
          }"
      >
        <el-button @click="showback()">返 回</el-button>
      </div>
    </div>
    <div v-show="propstype=='emit'&&activeName=='first'">
      <FilterTable
        ref="emittable"
        :columns="columns2"
        data-key
        :onColumnsChange="columns2 => this.columns2 = columns2"
        :dataSource="emitlist"
        :onRowSelectChange="selectChangeFun"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="emitAddfun()">添加</el-button>
        </template>
        <template slot="moreActions">
          <span @click="delRowsHandle1()">批量删除</span>
        </template>
      </FilterTable>
      <div
        :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'
          }"
      >
        <el-button @click="closeDrawer(1)">取 消</el-button>
        <el-button @click="closeDrawer(2)" type="primary">保 存</el-button>
      </div>
      <BaseDialog
        :visible.sync="visibleEmit"
        title="角色模板选择"
        destroyOnClose
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
      >
        <roleEmit @change="changeHandle1" @close="roleTemplateClose1" :getdata="propsdata" />
      </BaseDialog>
    </div>
    <div v-show="propstype=='add'&&activeName=='second'">
      <!-- 分配部门 -->
      <FilterTable
        ref="adddepttable"
        :columns="columns3"
        data-key
        :onColumnsChange="columns3 => this.columns3 = columns3"
        :dataSource="deptaddlist"
        :onRowSelectChange="selectdeptAdd"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="DeptaddRolefun()">添加</el-button>
        </template>
        <template slot="moreActions">
          <span @click="deldeptAdd()">批量删除</span>
        </template>
      </FilterTable>
      <div
        :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'
          }"
      >
        <el-button @click="deptcloseDrawer(1)">取 消</el-button>
        <el-button @click="deptcloseDrawer(2)" type="primary">保 存</el-button>
      </div>
      <BaseDialog
        :visible.sync="visibleDeptadd"
        title="部门选择"
        destroyOnClose
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
      >
        <deptAdd @change="changeDeptAddtable" @closeadd="closeDeptAddTable" :getdata="deptdata" />
      </BaseDialog>
    </div>
    <div v-show="propstype=='show'&&activeName=='second'">
      <!-- 分配部门 -->
      <FilterTable
        ref="showdepttable"
        :columns="columns4"
        data-key
        :onColumnsChange="columns4 => this.columns4 = columns4"
        :dataSource="deptshowlist"
      ></FilterTable>
      <div
        :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'
          }"
      >
        <el-button @click="deptcloseDrawer(1)">取 消</el-button>
      </div>
    </div>
    <div v-show="propstype=='emit'&&activeName=='second'">
      <!-- 分配部门 -->
      <FilterTable
        ref="emitdepttable"
        :columns="columns5"
        data-key
        :onColumnsChange="columns5 => this.columns5 = columns5"
        :dataSource="deptemitlist"
        :onRowSelectChange="selectdeptEmit"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="DeptEmitRolefun()">添加</el-button>
        </template>
        <template slot="moreActions">
          <span @click="deldeptEmit()">批量删除</span>
        </template>
      </FilterTable>
      <div
        :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'
          }"
      >
        <el-button @click="deptcloseDrawer(1)">取 消</el-button>
        <el-button @click="deptcloseDrawer(2)" type="primary">保 存</el-button>
      </div>
      <BaseDialog
        :visible.sync="visibleDeptemit"
        title="部门选择"
        destroyOnClose
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
      >
        <deptEmit @change="changeDeptEmittable" @closeadd="closeDeptEmitTable" :getdata="deptdata" />
      </BaseDialog>
    </div>
  </div>
</template>
<script>
import { getRolelist, setRolelist, getRoledetail, getRoleLists, setEmitRole, getdeptTree, setdeptaddRole, getdeptlistRole } from '@/api/common/auth/positionAuth/index';
import roleAdd from './role.vue';
import roleEmit from './roleEmit.vue';
import deptAdd from './deptadd.vue';
import deptEmit from './deptEmit.vue';
export default {
  name: 'zjdistributionTemplate',
  data() {
    this.savedata = null;
    this.addtable = null;
    this.emittable = null;
    this.showtable = null;
    this.adddepttable = null;
    this.emitdepttable = null;
    this.showdepttable = null;
    return {
      propstype: this.type,
      activeName: 'first',
      topFilterList: this.createToplist(),
      formshowList: this.createShowToplist(),
      propsdata: {
        id: this.getdata.id,
        code: this.getdata.code,
        codename: this.getdata.codename
      },
      visibleAdd: false, //添加弹窗
      visibleEmit: false,
      columns: this.createaddtable(),
      addtablelist: [],
      detailList: [],
      emitlist: [],
      columns1: this.createShowtable(),
      columns2: this.createEmittable(),
      selectedRows: [],
      selectedRows1: [],
      adddata: {
        dataSource: '10451001',
        dataType: '10461001',
        positionCode: '',
        positionName: '',
        departGmsList: [],
        roleGmsSelectList: []
      },
      // 部门
      treelist: [],
      columns3: this.createDeptAddtable(),
      columns4: this.createDeptShowtable(),
      columns5: this.createDeptEmittable(),
      deptaddlist: [],
      deptshowlist: [],
      deptemitlist: [],
      deptAddselect: [],
      visibleDeptadd: false,
      visibleDeptemit: false,
      deptdata: {
        id: '',
        name: '',
        codename: '',
        list: []
      }
    };
  },
  components: {
    roleAdd,
    roleEmit,
    deptAdd,
    deptEmit
  },
  mounted() {
    console.log(this.$refs);
    this.getdeptTreeFun({});
    if (this.type == 'show') {
      this.showtable = this.$refs.showtable.$refs.pageTable;
      this.showdepttable = this.$refs.showdepttable.$refs.pageTable;
      this.getRoledetails();
      this.getgetdeptlistRoleFun();
    } else if (this.type == 'add') {
      this.addtable = this.$refs.addtable.$refs.pageTable;
      this.adddepttable = this.$refs.adddepttable.$refs.pageTable;
    } else if (this.type == 'emit') {
      this.emittable = this.$refs.emittable.$refs.pageTable;
      this.emittashowdepttableble = this.$refs.showdepttable.$refs.pageTable;
      this.getRoleListsFun();
      this.getgetdeptlistRoleFun();
    }
  },
  props: ['type', 'getdata'],
  methods: {
    createToplist() {
      return [
        {
          type: 'INPUT',
          label: '职位代码',
          fieldName: 'positionCode',
          placeholder: '职位代码',
          initialValue: '',
          focus: () => {},
          rules: [{ required: true, message: '请输入职位代码', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '职位名称',
          fieldName: 'positionName',
          placeholder: '职位名称',
          initialValue: '',
          focus: () => {},
          rules: [{ required: true, message: '请输入职位名称', trigger: 'blur' }]
        }
      ];
    },
    createShowToplist() {
      return [
        {
          type: 'INPUT',
          label: '职位代码',
          disabled: true,
          fieldName: 'positionCode',
          placeholder: '职位代码',
          initialValue: this.getdata.code
        },
        {
          type: 'INPUT',
          label: '职位名称',
          disabled: true,
          fieldName: 'positionName',
          placeholder: '职位名称',
          initialValue: this.getdata.codename
        }
      ];
    },
    createaddtable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '角色代码',
          dataIndex: 'positionCode',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.roleCode}</span>;
          }
        },
        {
          title: '角色名称',
          dataIndex: 'positionName',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.roleName}</span>;
          }
        }
      ];
    },
    createShowtable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '角色代码',
          dataIndex: 'roleCode',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.roleCode}</span>;
          }
        },
        {
          title: '角色名称',
          dataIndex: 'roleName',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.roleName}</span>;
          }
        }
      ];
    },
    createEmittable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '角色代码',
          dataIndex: 'roleCode',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.roleCode}</span>;
          }
        },
        {
          title: '角色名称',
          dataIndex: 'roleName',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.roleName}</span>;
          }
        }
      ];
    },
    changeHandle(val) {
      this.savedata = val;
    },
    handleClick(val) {
      console.log(val, 'val');
    },
    addFun() {
      this.visibleAdd = true;
    },
    // 获取详情
    getRoledetails() {
      console.log('ajax');
      let that = this;
      getRoledetail({}, this.getdata.id)
        .then(function(res) {
          console.log(res, that);
          if (res.resultCode == 200) {
            that.detailList = res.data || [];
          }
        })
        .catch(function(res) {});
    },
    // 获取角色列表
    getRoleListsFun() {
      console.log('ajax');
      let that = this;
      getRoleLists(this.getdata)
        .then(function(res) {
          console.log(res, that);
          if (res.resultCode == 200) {
            if (that.type == 'emit') {
              that.emitlist = res.data || [];
            } else if ((that.type = 'add')) {
              that.addtablelist = res.data || [];
            }
          }
        })
        .catch(function(res) {});
    },
    getgetdeptlistRoleFun() {
      let that = this;
      getdeptlistRole(this.getdata)
        .then(function(res) {
          console.log(res, that);
          if (res.resultCode == 200) {
            if (that.type == 'emit') {
              that.deptemitlist = res.data || [];
            } else if ((that.type = 'add')) {
              that.deptaddlist = res.data || [];
            }
          }
        })
        .catch(function(res) {});
    },
    emitFun(data) {
      this.visibleEmit = true;
    },
    detailFun(data) {},
    // 选中
    selectChange(rows) {
      this.selectedRows = rows;
    },
    selectChangeFun(rows) {
      this.selectedRows1 = rows;
    },
    delRowsHandle() {
      this.addtable.EXECUTE_DELETE();
    },
    delRowsHandle1() {
      this.emittable.EXECUTE_DELETE();
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        if (this.type == 'add') {
          this.$refs.formpanel.SUBMIT_FORM();
          console.log(this.adddata, 'shuju');
          if (this.adddata != null) {
            if (this.type == 'add') {
              this.adddata.roleGmsSelectList = [...this.tablelist];
              await setRolelist(this.adddata);
              this.$emit('close', false);
            }
          }
        } else if (this.type == 'emit') {
          this.adddata.id = this.propsdata.id;
          this.adddata.roleGmsSelectList = [...this.emitlist];
          console.log(this.adddata, '编辑传参');
          await setEmitRole({ ...this.adddata });
          this.$emit('close', false);
        }
      }
    },
    // 编辑添加
    emitAddfun() {
      this.visibleEmit = true;
    },
    // 二级交互添加成功
    changepopHandle(data) {
      console.log(data);
      this.addtablelist = this.filterArr([...data, ...this.addtablelist], 'roleId');
      this.visibleAdd = false;
    },
    roleTemplateClose1(val) {
      console.log(val);
      this.visible = false;
    },
    changeHandle1(data) {
      console.log(data);
      let arr = data.list;
      this.emitlist = this.filterArr([...this.emitlist, ...arr], 'roleId');
      console.log(this.emitlist);
      this.visibleEmit = false;
    },
    // 添加弹窗关闭
    roleAddClose(val) {
      this.visibleAdd = false;
    },
    // 详情弹窗关闭
    showback() {
      this.$emit('close', false);
    },

    // 部门相关
    getdeptTreeFun(data) {
      let that = this;
      getdeptTree()
        .then(function(res) {
          console.log(res, that);
          if (res.resultCode == 200) {
            console.log(res.data, 'data');
            that.deleteRes(res.data);
            that.deptdata.list = that.getJsonTree(res.data);
          }
        })
        .catch(function(res) {});
    },
    createDeptAddtable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '部门代码',
          dataIndex: 'orgCode',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.orgCode}</span>;
          }
        },
        {
          title: '部门名称',
          dataIndex: 'orgName',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.orgName}</span>;
          }
        }
      ];
    },
    createDeptEmittable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '部门代码',
          dataIndex: 'orgCode',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.orgCode}</span>;
          }
        },
        {
          title: '部门名称',
          dataIndex: 'orgName',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.orgName}</span>;
          }
        }
      ];
    },
    createDeptShowtable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '部门代码',
          dataIndex: 'orgCode',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.orgCode}</span>;
          }
        },
        {
          title: '部门名称',
          dataIndex: 'orgName',
          sorter: false,
          filter: false,
          render: props => {
            return <span>{props.row.orgName}</span>;
          }
        }
      ];
    },
    selectdeptAdd(row) {
      this.deptAddselect = row;
    },
    selectdeptEmit(row) {
      this.deptEmitselect = row;
    },
    DeptaddRolefun() {
      this.visibleDeptadd = true;
    },
    DeptEmitRolefun() {
      this.visibleDeptemit = true;
    },
    deldeptAdd() {
      this.adddepttable.EXECUTE_DELETE();
    },
    deldeptEmit() {
      this.emitdepttable.EXECUTE_DELETE();
    },
    async deptcloseDrawer(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        if (this.type == 'add') {
          this.$refs.formpanel.SUBMIT_FORM();
          console.log(this.adddata, 'shuju');
          if (this.adddata != null) {
            if (this.type == 'add') {
              this.adddata.departGmsList = [...this.deptaddlist];
              await setdeptaddRole(this.adddata);
              this.$emit('close', false);
            }
          }
        } else if (this.type == 'emit') {
          this.adddata.id = this.propsdata.id;
          this.adddata.departGmsList = [...this.emitlist];
          console.log(this.adddata, '编辑传参');
          await setEmitRole({ ...this.adddata });
          this.$emit('close', false);
        }
      }
    },
    changeDeptAddtable(data) {
      console.log(data);
      this.deptaddlist = this.filterArr(data.list, 'id');
      this.visibleDeptadd = false;
    },
    changeDeptEmittable(data) {
      console.log(data);
      this.deptemitlist = this.filterArr(data.list, 'id');
      this.visibleDeptemit = false;
    },
    closeDeptEmitTable(data) {
      this.visibleDeptemit = false;
    },
    closeDeptAddTable(data) {
      this.visibleDeptadd = false;
    },
    //数组去重方法
    filterArr(arr, attribute) {
      var new_arr = [];
      var json_arr = [];
      for (var i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
          //  -1代表没有找到
          new_arr.push(arr[i][attribute]); //如果没有找到就把这个name放到arr里面，以便下次循环时用
          json_arr.push(arr[i]);
        } else {
        }
      }
      return json_arr;
    },
    // 改变tree数据
    deleteRes(res) {
      let result = [];
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        let pid = res[i].parent;
        let oid = res[i].id;
        result[oid] = pid;
      }
      for (let j = 0; j < res.length; j++) {
        // 一级父节点跳过
        if (res[j].parent == '#') continue;
        if (res[j] && result[res[j].parent] == null) {
          let index = j;
          j = 0;
          delete result[res[index].id];
          res.splice(index, 1);
        }
      }
    },
    getJsonTree(data, id = 'id', parentId = 'parentId') {
      data.forEach(function(item) {
        delete item.children;
      });
      const map = {};
      data.forEach(function(item) {
        map[item[id]] = item;
      });

      const val = [];
      data.forEach(function(item) {
        const parent = map[item[parentId]];

        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          val.push(item);
        }
      });

      return val;
    }
  }
};
</script>
